<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date
                placeholder="请选择申请时间"
                v-model="model.createTime"
                :show-time="true"
                date-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
                disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
              <select-user-by-dep placeholder="请选择申请人" v-model="model.handlerId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDeptId">
              <j-select-depart placeholder="请选择申请部门" v-model="model.applyDeptId" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="costTeamId">
              <select-team-input
                placeholder="请选择申请人所属团队"
                :disabled="formDisabled"
                v-model="model.costTeamId"
                :tdlx="3" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <!-- <a-col :span="8" :hidden="true">
                  <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                    <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                    <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                    <j-date placeholder="请选择申请时间" v-model="model.createTime" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm" style="width: 100%" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
                    <select-user-by-dep placeholder="请选择申请人" v-model="model.handlerId" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDeptId">
                    <j-select-depart placeholder="请选择申请部门" v-model="model.applyDeptId" disabled />
                  </a-form-model-item>
                </a-col> -->
              <a-col :span="8" v-if="changeType">
                <a-form-model-item label="选择培训档案" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="finalId">
                  <SelectHrTrainingChangeInput
                    :disabled="formDisabled"
                    v-model="model.finalId"
                    placeholder="请选择选择培训档案"
                    @back="handleChangeBack" />
                </a-form-model-item>
              </a-col>
              <template v-if="revokedType">
                <a-divider>作废信息</a-divider>
                <a-col :span="8">
                  <a-form-model-item
                    label="选择培训档案"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="finalId">
                    <SelectHrTrainingChangeInput
                      :disabled="formDisabled"
                      v-model="model.finalId"
                      placeholder="请选择选择培训档案"
                      @back="handleChangeBack" />
                  </a-form-model-item>
                </a-col>
                <!-- <a-col :span="8">
                  <a-form-model-item
                    label="申请人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="invalidationProposer">
                    <select-user-by-dep placeholder="请选择申请人" v-model="model.invalidationProposer" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="申请部门"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="invalidationDepartId">
                    <j-select-depart placeholder="请选择申请部门" v-model="model.invalidationDepartId" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item
                    label="申请时间"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="invalidationCreateTime">
                    <j-date
                      placeholder="请选择申请时间"
                      v-model="model.invalidationCreateTime"
                      :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss"
                      style="width: 100%"
                      disabled />
                  </a-form-model-item>
                </a-col> -->
              </template>
              <a-col :span="8">
                <a-form-model-item label="培训分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="trainingCategory">
                  <j-dict-select-tag
                    :disabled="formDisabled || revokedType || changeType"
                    type="list"
                    v-model="model.trainingCategory"
                    dictCode="training_category"
                    placeholder="请选择培训分类" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="培训目的"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="trainingObjective">
                  <a-input
                    :disabled="formDisabled || revokedType"
                    :max-length="50"
                    v-model="model.trainingObjective"
                    placeholder="请输入培训目的"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="培训地点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="trainingAddress">
                  <a-input
                    :disabled="formDisabled || revokedType"
                    :max-length="50"
                    v-model="model.trainingAddress"
                    placeholder="请输入培训地点"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="获得证书名称"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="certificateName">
                  <a-input
                    :disabled="formDisabled || revokedType"
                    :max-length="50"
                    v-model="model.certificateName"
                    placeholder="请输入获得证书名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="培训开始日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="trainingStartDate">
                  <j-date
                    :disabled="formDisabled || revokedType"
                    :disabled-date="disableTrainingStartDate"
                    placeholder="请选择培训开始日期"
                    :showToday="false"
                    v-model="model.trainingStartDate"
                    date-format="YYYY-MM-DD"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="培训结束日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="trainingEndDate">
                  <j-date
                    :disabled-date="disableTrainingEndDate"
                    :disabled="formDisabled || revokedType"
                    placeholder="请选择培训结束日期"
                    :showToday="false"
                    v-model="model.trainingEndDate"
                    date-format="YYYY-MM-DD"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="服务开始日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="serviceStartDate">
                  <j-date
                    :disabled="formDisabled || revokedType"
                    placeholder="请选择服务开始日期"
                    v-model="model.serviceStartDate"
                    date-format="YYYY-MM-DD"
                    style="width: 100%"
                    @change="handleServiceLimitBack" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="培训服务期限"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="trainingServiceLimit">
                  <j-dict-select-tag
                    :disabled="formDisabled || revokedType"
                    type="list"
                    v-model="model.trainingServiceLimit"
                    dictCode="training_service_limit"
                    placeholder="请选择培训服务期限"
                    @input="handleServiceLimitBack" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="服务结束日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="serviceEndDate">
                  <j-date
                    disabled
                    placeholder="请选择服务结束日期"
                    v-model="model.serviceEndDate"
                    date-format="YYYY-MM-DD"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="培训费用(元/人)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="trainingFee">
                  <a-input-number
                    :disabled="formDisabled || revokedType"
                    :max="999999999"
                    :min="0"
                    :precision="2"
                    v-model="model.trainingFee"
                    placeholder="请输入培训费用"
                    @blur="handleTrainingFeeChange"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="培训费用合计(元)"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="trainingFeeTotal">
                  <a-input-number
                    disabled
                    :max="999999999"
                    :min="0"
                    :precision="2"
                    v-model="model.trainingFeeTotal"
                    placeholder="请输入培训费用合计"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item
                  label="培训人员"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <ErpHrTrainingApplyFormPersonList
                    ref="trainingApplyFormRef"
                    :disabled="formDisabled || revokedType"
                    @applyDetailData="handleTrainingFeeChange" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea
                    :disabled="formDisabled || revokedType || changeType"
                    :max-length="500"
                    v-model="model.remark"
                    rows="4"
                    placeholder="请输入备注" />
                </a-form-model-item>
              </a-col>

              <a-col :span="24" v-if="changeType">
                <a-form-model-item label="变更描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="changeRemark">
                  <a-textarea
                    :disabled="formDisabled"
                    :max-length="500"
                    v-model="model.changeRemark"
                    rows="4"
                    placeholder="请输入变更描述" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24" v-if="revokedType">
                <a-form-model-item label="作废描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invalidRemark">
                  <a-textarea
                    :max-length="500"
                    :disabled="formDisabled"
                    v-model="model.invalidRemark"
                    rows="4"
                    placeholder="请输入作废描述" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="attachment">
                  <j-upload
                    v-if="!formDisabled"
                    :disabled="formDisabled"
                    v-model="model.attachment"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.attachment)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-collapse>
      </a-form-model>
      <common-flow-list
        v-if="formBpm && model.bpmStatus !== '1'"
        :formData="formData"
        style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button
          type="primary"
          v-if="formBpm"
          :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }"
          @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>

    <!-- 详情开始 -->
    <erp-project-report-modal ref="projectForm"></erp-project-report-modal>
    <!-- 详情结束 -->
    <ErpHrTrainingApplyFormPrint
      v-if="formBpm"
      class="print_style"
      id="hrTraningApplyFormPrint"
      :formData="model"
      :formDataHistory="formData"></ErpHrTrainingApplyFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import ErpHrTrainingApplyFormPersonList from './reference/ErpHrTrainingApplyFormPersonList';
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import CommonFirstFlowList from '@/views/components/CommonFirstFlowList.vue';
import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
import Print from '@/utils/print/printarea.js';
import ErpHrTrainingApplyFormPrint from './ErpHrTrainingApplyFormPrint.vue';
import SelectPurchaseApplyInput from './SelectPurchaseApplyInput'
import SelectHrTrainingChangeInput from './SelectHrTrainingChangeInput'

export default {
    name: 'ErpPurchaseApplyInvitationForm',
    mixins: [viewFile],
    components: {
      ErpProjectReportModal,
      ViewFileModal,
      SelectTeamInput,
      SelectUserByDep,
      ErpHrTrainingApplyFormPersonList,
      SelectProjectInput,
      CommonFlowList,
      CommonFirstFlowList,
      SelectPurchaseApplyInput,
      SelectHrTrainingChangeInput, // 变更申请选择档案
      ErpHrTrainingApplyFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        userName: '',
        activeKey: ['1', '2', '3'],
        model: {
          checkStatus: 0,
          billNo: null,
          finalId: null,
          invalidRemark: ''
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          costTeamId: [
            { required: true, message: '请选择申请人所属团队!', trigger: 'change' }
          ],
          finalId: [
            { required: true, message: '请选择培训档案!', trigger: 'change' }
          ],
          changeRemark: [
            { required: true, message: '请输入变更描述!', trigger: 'blur' }
          ],
          // 培训分类
          trainingCategory: [
            { required: true, message: '请选择培训分类!', trigger: 'change' }
          ],
          // 培训服务期限
          trainingServiceLimit: [
            { required: true, message: '请选择培训服务期限!', trigger: 'change' }
          ],
          // 培训开始日期
          trainingStartDate: [
              { required: true, message: '请选择培训开始日期!', trigger: 'change' }
          ],
          // 培训结束日期
          trainingEndDate: [
              { required: true, message: '请选择培训结束日期!', trigger: 'change' }
          ],
          // 服务开始日期
          serviceStartDate: [
              { required: true, message: '请选择服务开始日期!', trigger: 'change' }
          ],
          // 服务结束日期
          serviceEndDate: [
              { required: true, message: '请选择服务结束日期!', trigger: 'change' }
          ],
          trainingFeeTotal: [
              { required: true, message: '请输入培训费用合计!', trigger: 'change' }
          ],
          trainingFee: [
              { required: true, message: '请输入培训费用!', trigger: 'change' }
          ],
          // 培训目的
          trainingObjective: [
              { required: true, message: '请输入培训目的!', trigger: 'blur' }
          ],
          // 培训地点
          trainingAddress: [
              { required: true, message: '请输入培训地点!', trigger: 'blur' }
          ],
          // 证书名称
          certificateName: [
            { required: true, message: '请输入证书名称!', trigger: 'blur' }
          ],
          invalidRemark: [
            { required: true, message: '请输入作废描述!', trigger: 'blur' }
          ]
        },
        url: {
          add: '/api/erp/hr/training/erpHrTrainingApply/add',
          edit: '/api/erp/hr/training/erpHrTrainingApply/edit',
          queryById: '/api/erp/hr/training/erpHrTrainingApply/queryById',
          generatedFormNumber: '/api/erp/base/generatedFormNumber',
          queryVerification: '/api/erp/hr/training/erpHrTrainingApply/referencedVerification',
          queryVerificationCancelling: '/api/erp/hr/training/erpHrTrainingApply/referencedVerificationCancelling',
          getBizHisProcessNodeInfo: '/api/erpmng/act/process/extActProcessNode/getBizHisProcessNodeInfo'
        },
        details: [],
        showBusinessSegment: false,
        revokedType: false,
        changeType: false,
        purchaseBillIdBackups: null
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      // 选择培训档案
      handleChangeBack (val) {
        this.handleModelData(val[0], 'lastBillId')
        this.$set(this.model, 'finalId', val[0].id)
      },
      // purchaseInfoBack(item) {
      //   const that = this
      //   // 判断不为空
      //   if (!!this.model.purchaseBillId && item.length > 0) {
      //     // 判断公司是否变化
      //     // if(this.purchaseBillIdBackups !== item[0].id)
      //     getAction(this.url.queryVerification, { id: item[0].id }).then(res => {
      //       if (res.result == '校验通过') {
      //         getAction(this.url.queryVerificationCancelling, { id: item[0].id }).then(response => {
      //           if (response.result == '校验通过') {
      //             // 确认后进行改变
      //             that.purchaseBillIdBackups = item[0].id
      //             that.handleModelData(item[0])
      //             that.model.purchaseBillId = item[0].id
      //           } else {
      //             that.$message.warning(response.message)
      //             that.model.purchaseBillId = that.purchaseBillIdBackups
      //             if (!that.purchaseBillIdBackups) {
      //               that.handleModelData()
      //             }
      //           }
      //         })
      //       } else {
      //         that.$message.warning(res.message)
      //         that.model.purchaseBillId = that.purchaseBillIdBackups
      //         if (!that.purchaseBillIdBackups) {
      //           that.handleModelData()
      //         }
      //       }
      //     })
      //   } else {
      //     that.handleModelData()
      //   }
      // },
      handleModelData(val, type) {
        if (val && val.id) {
          // 选择单据 处理原表单数据
          this.$set(this.model, 'invalidationProposer', val.handlerId || '')
          this.$set(this.model, 'invalidationDepartId', val.applyDeptId || '')
          this.$set(this.model, 'invalidationCreateTime', val.createTime || '')
          // this.$set(this.model, 'costTeamId', val.costTeamId || '')
          this.$set(this.model, 'trainingCategory', val.trainingCategory || '') // 培训分类
          this.$set(this.model, 'trainingServiceLimit', val.trainingServiceLimit || '') // 培训服务期限
          this.$set(this.model, 'trainingStartDate', val.trainingStartDate || '') // 培训开始日期
          this.$set(this.model, 'trainingEndDate', val.trainingEndDate || '') // 培训结束日期
          this.$set(this.model, 'serviceStartDate', val.serviceStartDate || '') // 服务开始日期
          this.$set(this.model, 'serviceEndDate', val.serviceEndDate || '') // 服务结束日期
          this.$set(this.model, 'trainingFee', val.trainingFee || '') // 培训费用
          this.$set(this.model, 'trainingFeeTotal', val.trainingFeeTotal || '') // 培训费用合计
          this.$set(this.model, 'trainingObjective', val.trainingObjective) // 培训目的
          this.$set(this.model, 'trainingAddress', val.trainingAddress || '') // 培训地点
          this.$set(this.model, 'certificateName', val.certificateName || '') // 证书名称
          this.$set(this.model, 'remark', val.remark || '') // 备注
          // this.$set(this.model, 'attachment', val.attachment || '') // 附件
          this.$set(this.model, 'finalNo', val.finalNo || '') // 档案编号
          this.$refs.trainingApplyFormRef.loadData(1, type, val[type])
        } else {
            // 选择单据 处理原表单数据
          this.$set(this.model, 'invalidationProposer', '')
          this.$set(this.model, 'invalidationDepartId', '')
          this.$set(this.model, 'invalidationCreateTime', '')
          // this.$set(this.model, 'costTeamId', '')
          this.$set(this.model, 'trainingCategory', '')
          this.$set(this.model, 'trainingServiceLimit', '')
          this.$set(this.model, 'trainingStartDate', '')
          this.$set(this.model, 'trainingEndDate', '')
          this.$set(this.model, 'serviceStartDate', '')
          this.$set(this.model, 'serviceEndDate', '') // 服务结束日期
          this.$set(this.model, 'trainingFee', '') // 培训费用
          this.$set(this.model, 'trainingFeeTotal', '') // 培训费用合计
          this.$set(this.model, 'trainingObjective', '')
          this.$set(this.model, 'trainingAddress', '')
          this.$set(this.model, 'certificateName', '')
          this.$set(this.model, 'remark', '')
          // this.$set(this.model, 'attachment', '')
          this.$set(this.model, 'finalNo', '') // 档案编号
          this.$refs.trainingApplyFormRef.dataSource = []
        }
        this.handleServiceLimitBack()
      },
      // 培训结束日期禁用
      disableTrainingEndDate(current) {
        if (this.model.trainingStartDate) {
          return current && current < moment(this.model.trainingStartDate).endOf('day')
        } else {
          return null
        }
      },
      disableTrainingStartDate(current) {
        if (this.model.trainingEndDate) {
          return current >= moment(this.model.trainingEndDate).subtract('day')
        } else {
          return null
        }
      },
      // 类型选择
      handleServiceLimitBack () {
        if (this.model.serviceStartDate && this.model.trainingServiceLimit) {
          this.$set(this.model, 'serviceEndDate', moment(this.model.serviceStartDate).add(this.model.trainingServiceLimit, 'day').format('YYYY-MM-DD'))
        } else {
          this.$set(this.model, 'serviceEndDate', '') // 服务结束日期
        }
      },
      // 填写培训费用
      handleTrainingFeeChange () {
        let details = this.$refs.trainingApplyFormRef.submitForm() || []
        let total = ((this.model.trainingFee ? this.model.trainingFee : 0) * details.length).toFixed(2) || '0.00'
        this.$set(this.model, 'trainingFeeTotal', total)
      },
      getBillNo (type) {
        const that = this
        var prefix = ''
        if (type == 'apply') {
          prefix = 'PXSQ'
        } else if (type == 'change') {
          prefix = 'BGPXSQ'
        } else {
          prefix = 'ZFPXSQ'
        }
        getAction(this.url.generatedFormNumber, { prefix: prefix, subSystemCode: '02' }).then(res => {
          if (res.success) {
            that.model.billNo = res.result// 单据编号
            if (type == 'apply') {
              that.model.bpmBizTitle = that.userName + '-' + that.model.billNo// 标题
            } else if (type == 'change') {
              that.$set(that.model, 'bpmBizTitle', that.userName + '-' + that.model.billNo)
            } else {
              that.$set(that.model, 'bpmBizTitle', that.userName + '-' + that.model.billNo)
            }
          }
        })
      },
      add (value) {
        this.revokedType = value == 'cancel'
        this.changeType = value == 'change'
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.modelDefault.handlerId = this.userInfo().empId; // 当前登录人
        this.modelDefault.applyDeptId = this.userInfo().deptId; // 当前登录人部门
        this.modelDefault.createTime = moment().format('YYYY-MM-DD HH:mm');
        this.modelDefault.trainingServiceLimit = '1094';
        if (value == 'cancel') {
          this.$refs['form'].clearValidate();
          this.model = Object.assign({}, {
            billNo: '',
            finalId: '',
            invalidRemark: ''
          })
          this.purchaseBillIdBackups = null
          // this.$refs.trainingApplyFormRef.dataSource = []
          this.modelDefault.trainingType = 'cancel';
        } else if (value == 'change') {
          this.modelDefault.trainingType = 'change';
        } else {
          this.modelDefault.trainingType = 'apply';
        }
        this.getBillNo(this.modelDefault.trainingType) // 获取单据编号
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs['form'].clearValidate();
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model = Object.assign({}, record);
        this.revokedType = this.model.trainingType == 'cancel'
        this.changeType = this.model.trainingType == 'change'
        this.handleServiceLimitBack()
        // if (this.revokedType) {
        //   this.validatorRules = {
        //     purchaseBillId: [
        //       { required: true, message: '请选择单据名称!', trigger: 'change' }
        //     ],
        //     invalidationReason: [
        //       { required: true, message: '请输入作废理由!', trigger: 'blur' }
        //     ]
        //   }
        //   this.purchaseBillIdBackups = this.model.purchaseBillId
        // } else {
        //   this.validatorRules = {
        //     costTeamId: [
        //       { required: true, message: '请选择团队!', trigger: 'change' }
        //     ],
        //     trainingCategory: [
        //       { required: true, message: '请选择培训分类!', trigger: 'blur' }
        //     ],
        //     trainingServiceLimit: [
        //       { required: true, message: '请选择培训服务期限!', trigger: 'change' }
        //     ],
        //     trainingStartDate: [
        //       { required: true, message: '请选择培训开始日期!', trigger: 'change' }
        //     ],
        //     trainingEndDate: [
        //       { required: true, message: '请选择培训结束日期!', trigger: 'change' }
        //     ],
        //     serviceStartDate: [
        //       { required: true, message: '请选择服务开始日期!', trigger: 'change' }
        //     ],
        //     serviceEndDate: [
        //       { required: true, message: '请选择服务结束日期!', trigger: 'change' }
        //     ],
        //     trainingObjective: [
        //       { required: true, message: '请输入培训目的!', trigger: 'blur' }
        //     ],
        //     trainingAddress: [
        //       { required: true, message: '请输入培训地点!', trigger: 'blur' }
        //     ],
        //     certificateName: [
        //       { required: true, message: '请输入证书名称!', trigger: 'blur' }
        //     ]
        //   }
        // }
        if (this.model.id) {
          this.$nextTick(() => {
            this.$refs.trainingApplyFormRef.loadData(1, 'billId', this.model.id)
          })
        } else {
          this.$nextTick(() => {
            this.$refs.trainingApplyFormRef.dataSource = []
          })
        }
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          let details = this.$refs.trainingApplyFormRef.submitForm()
          if (!details.length > 0) {
            this.$message.warning('请添加培训人员！');
            this.$emit('unButtonDisable');
            return
          }
          // if (this.revokedType) {
          //   getAction(this.url.queryVerification, { id: that.model.purchaseBillId }).then(res => {
          //     if (res.success) {
          //       getAction(this.url.queryVerificationCancelling, { id: that.model.purchaseBillId }).then(resp => {
          //         if (resp.success) {
          //           // 触发表单验证
          //           this.$refs.form.validate(valid => {
          //             if (valid) {
          //               that.submit(type)
          //             } else {
          //               that.$emit('unButtonDisable')
          //             }
          //           })
          //         } else {
          //           that.$message.warning(resp.message);
          //           that.$emit('unButtonDisable');
          //         }
          //       })
          //     } else {
          //       that.$message.warning(res.message);
          //       that.$emit('unButtonDisable');
          //     }
          //   })
          //   return
          // }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        let details = this.$refs.trainingApplyFormRef.submitForm() || []
        this.model.erpHrTrainingDetailList = details
        this.model.applyTeamId = this.model.costTeamId ? this.model.costTeamId : ''
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#hrTraningApplyFormPrint',
          popTitle: '培训申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
      // backUserInfo(data) {
      //   this.model.applicant = data[0].orgDepart;//申请人单位
      //   this.model.applyDeptId = data[0].departmentId;//申请人部门
      // }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
